# app/database/neo4j_connector.py
from neo4j import GraphDatabase
import logging
import os
from dotenv import load_dotenv  # 导入 load_dotenv
# 设置日志
logger = logging.getLogger("neo4j_connector")

# 加载环境变量
load_dotenv()
class Neo4jConnector:
    def __init__(self):
        try:
            self.driver = GraphDatabase.driver(os.getenv("NEO4J_URI"), auth=(os.getenv("NEO4J_USER"), os.getenv("NEO4J_PASSWORD")))
            logger.info('Connected to Neo4j database')
        except Exception as e:
            logger.error(f"Error while connecting to Neo4j: {e}")

    def query_related_concepts(self, category):
        def run_query(tx):
            query = f"MATCH (c:Category {{name: '{category}'}})-[:RELATED_TO]->(r) RETURN r.name AS name, r.description AS description"
            result = tx.run(query)
            return [record.data() for record in result]

        try:
            with self.driver.session() as session:
                return session.read_transaction(run_query)
        except Exception as e:
            logger.error(f"Error while querying Neo4j: {e}")
            return []
